<?php

class WSB_View_Helper_ModelSelect
{

	private static $_instance = 0;
    private $_url;
    private $_currentId;
    private $_html;
    private $_model;

    public function modelSelect($model, $url)
	{
    	self::$_instance++;
    	$this->_model = $model;
    	$this->_html = '';
        $this->_url = $url;
        $this->_currentId = $model->getPrimaryValue();
		$node = WSB_Node_Page::getTree();
		$this->_buildOptions($node);
		return sprintf(
            '<script type="text/javascript">
                var url = \'%1$s\';
                function modelSelectJumpUrl%3$s(id)
	{
                    window.location.href=url.replace(\'#\', id);
                }
            </script>
            <select onchange="modelSelectJumpUrl%3$s(this.options[this.selectedIndex].value);">%2$s</select>',
            $this->_url,
            $this->_html,
            self::$_instance
        );
    }

    private function _buildOptions(WSB_Node_Page $node)
	{
        $models = $this->_model->fetchAll('deleted=0', $this->_model->getOrder(), 100);
        foreach($models AS $model) {
            $this->_html .= $this->_buildOption($model->getPrimaryValue(), $model->getTitle());
        }
    }

    private function _buildOption($id, $value)
	{
        $indent = '';
        $selected = '';
        if($id == $this->_currentId) {
            $selected = ' selected="selected"';
        }
        return sprintf('<option value="%s"%s>%s</option>', $id, $selected, $this->_substr($value));
    }

    private function _substr($string)
	{
        return substr($string, 0, 50);
    }

}
